package com.earogya.logic.medical_records;

import java.util.Calendar;

import org.apache.struts.ehr.medical_records.model.DischargePatient;

import com.earogya.Constants;

import ca.uhn.hl7v2.HL7Exception;
import ca.uhn.hl7v2.model.DataTypeException;
import ca.uhn.hl7v2.model.v251.message.ADT_A03;

/***
 * Create ADT A03 message to discharge a patient.
 * @author Chamendri
 *
 */
public class CreateADTA03 {

	private DischargePatient dischargePatient;
	private ADT_A03 adtMsg;
	
	/**
	 * Accepts DischargePatient object
	 * @param dischargePatient
	 */
	public CreateADTA03(DischargePatient dischargePatient){
		this.adtMsg=new ADT_A03();
		this.dischargePatient=dischargePatient;
	}
	
	/**
	 * Creates HL7 ADT A03 message to discharge the patient.
	 * @param sendingFacility
	 * @return
	 * @throws HL7Exception
	 */
	public String createMessage(String sendingFacility) throws HL7Exception{
		this.addMessageHeader(sendingFacility);
		this.addDischargeInformation();
		return adtMsg.getMessage().encode();
	}
	
	/**
	 * Add MSH segment to ADT A03 message
	 * @param sendingFacility
	 * @throws DataTypeException
	 */
	private void addMessageHeader(String sendingFacility) throws DataTypeException{
		adtMsg.getMSH().getFieldSeparator().setValue("|");
		adtMsg.getMSH().getEncodingCharacters().setValue("^~\\&");
		adtMsg.getMSH().getDateTimeOfMessage().getTime().setValue(Calendar.getInstance().getTime());
		adtMsg.getMSH().getMessageType().getMsg1_MessageCode().setValue("ADT");
		adtMsg.getMSH().getMessageType().getTriggerEvent().setValue("A03");
		adtMsg.getMSH().getSendingApplication().getUniversalID().setValue(Constants.SENDING_APPLICATION);
		adtMsg.getMSH().getVersionID().getVersionID().setValue(Constants.HL7_VERSION);
		adtMsg.getMSH().getSendingFacility().getUniversalID().setValue(sendingFacility);
		adtMsg.getMSH().getReceivingApplication().getUniversalID().setValue(Constants.RECEIVING_APPLICATION_PATIENT_VISIT_SERVICE);
		adtMsg.getMSH().getReceivingFacility().getUniversalID().setValue(sendingFacility);
	}
	
	/**
	 * Add PIC, PV1 segments to ADT A03 message.
	 * @throws DataTypeException
	 */
	private void addDischargeInformation() throws DataTypeException{
		adtMsg.getPID().getPatientID().getIDNumber().setValue(String.valueOf(dischargePatient.getPatientId()));
		adtMsg.getPV1().getConsultingDoctor(0).getIDNumber().setValue(String.valueOf(dischargePatient.getDischargeConsultantId()));
		adtMsg.getPV1().getDischargeDateTime(0).getTime().setValue(dischargePatient.getDischargeDate());
		adtMsg.getPV1().getDischargeDisposition().setValue(dischargePatient.getComments());
	}
}
